package com.shanzmoo.db.store.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.shanzmoo.db.store.entity.StoreStockEntity;
import com.shanzmoo.db.store.entity.StoreStockIoEntity;
import com.shanzmoo.db.store.entity.vo.StoreStockVO;
import com.shanzmoo.db.store.entity.query.StoreStockQuery;
import com.shanzmoo.db.store.mapper.StoreStockMapper;
import com.shanzmoo.db.store.service.IStoreStockIoService;
import com.shanzmoo.db.store.service.IStoreStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 库存实时明细 服务实现类
 *
 * @author fs 2021-03-09
 */
@Service
public class StoreStockServiceImpl extends ServiceImpl<StoreStockMapper, StoreStockEntity>
        implements IStoreStockService {

    @Autowired
    private IStoreStockIoService storeStockIoService;

    @Override
    public List<StoreStockVO> queryPageList(StoreStockQuery query) {
        return baseMapper.queryPageList(query);
    }

    @Override
    public StoreStockEntity getBySkuAndStoreCode(String sku, String storeCode) {
        Assert.isTrue(StrUtil.isNotEmpty(sku),"未获取到sku信息，库存查询失败");
        Assert.isTrue(StrUtil.isNotEmpty(storeCode),"未获取到仓库编码信息，库存查询失败");

        return this.lambdaQuery()
                .eq(StoreStockEntity::getDeleted, false)
                .eq(StoreStockEntity::getSku, sku)
                .eq(StoreStockEntity::getStoreCode, storeCode)
                .one();
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.MANDATORY)
    @Override
    public void updateStockByIo(StoreStockIoEntity ioEntity, Integer versionId) {
        String sku = ioEntity.getSku();
        String storeCode = ioEntity.getStoreCode();
        Boolean flow = ioEntity.getFlow();
        Integer skuNum = ioEntity.getSkuNum();

        Assert.isTrue(StrUtil.isNotEmpty(sku),"未获取到sku信息，库存更新失败");
        Assert.isTrue(StrUtil.isNotEmpty(storeCode),"未获取到仓库编码信息，库存更新失败");
        Assert.isTrue(ObjectUtil.isNotNull(flow),"未获取到库存流向，库存更新失败");
        Assert.isTrue(ObjectUtil.isNotNull(skuNum),"未获取到库存更新数量，库存更新失败");

        Integer row = baseMapper.updateStock(sku, storeCode, flow ? skuNum:-skuNum, versionId);
        Assert.isTrue(1 == row,"数据异常，库存更新失败");

        if (!flow) {
            StoreStockEntity stockEntity = this.getBySkuAndStoreCode(sku, storeCode);
            Assert.isTrue(stockEntity.getSkuNum() >= 0,"sku：" + stockEntity.getSku() + " 库存不足, 扣减失败");
        }

        // 保存库存流水
        boolean ioSave = storeStockIoService.save(ioEntity);
        Assert.isTrue(ioSave,"库存写入失败，库存更新失败");
    }
}
